import React, { useEffect, useState } from 'react';
import { Image, ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { Button, Card, Tabs } from '@ant-design/react-native';
import { getScreenWidth } from '@/utils/auto';
import axios from 'axios';
import { router } from 'expo-router';

const MyOrder = () => {
    const [orders, setOrders] = useState<any>([]);
    const [activeTab, setActiveTab] = useState(0);

    const tabs = [
        { title: '全部' },
        { title: '待付款' },
        { title: '待收货' },
        { title: '已完成' },
        { title: '待评价' },
    ];

    const getOrders = async () => {
        try {
            const response = await axios.get('http://192.168.13.227:3000/hw/getOrder');
            setOrders(response.data.data);
        } catch (error) {
            console.error('Error fetching orders:', error);
        }
    };

    useEffect(() => {
        getOrders();
    }, []);

    const filterOrders = (tabIndex: number) => {
        return orders.filter((order: any) => {
            switch (tabIndex) {
                case 0: return true; // All orders
                case 1: return order.status === '待付款';
                case 2: return order.status === '待收货';
                case 3: return order.status === '已完成';
                case 4: return order.status === '待评价';
                default: return true;
            }
        });
    };

    const renderContent = (tabIndex: number) => {
        const filteredOrders = filterOrders(tabIndex)

        return (
            <ScrollView style={{ backgroundColor: "rgb(245,248,255)" }}>
                {filteredOrders.reverse().map((order: any) => (
                    <Card key={order._id} style={styles.order}>
                        <Card.Header
                            title={order.name}
                            thumbStyle={{ width: 30, height: 30 }}
                            thumb={<Image source={{ uri: order.img[0] }} style={{ width: 40, height: 40 }} />}
                            extra={order.status == 1 ? '待付款' : order.status == 2 ? '待收货' : order.status == 3 ? '已完成' : '待评价'}
                        />
                        <Card.Body>
                            <View style={{ height: 100 }}>
                                <Text style={{ marginLeft: 16 }}>{order.detail}</Text>
                            </View>
                        </Card.Body>
                        <Card.Footer
                            content={`Price: ${order.price}`}
                            extra={changeButton(order.status)}
                            style={{ borderTopWidth: 1, borderColor: '#ccc', padding: 10 }}
                        />
                    </Card>
                ))}
            </ScrollView>
        );
    };

    const changeButton = (status: number) => {
        if (status == 1) {
            return (
                <Button type="primary" size='small' onPress={() => {
                    router.push({
                        pathname: '/buyPage'
                    })
                }}>付款</Button>
            )
        } else if (status == 2) {
            return (
                <Button type="primary" size='small' onPress={() => handleConfirmReceipt(order)}>确认收货</Button>
            )
        }
        else if (status == 3) {
            return (
                <Button type="primary" size='small' onPress={() => handleEvaluation(order)}>评价</Button>
            )
        }
        else if (status == 4) {
            return (
                <Button type="primary" size='small' onPress={() => handleDelete(order)}>删除</Button>
            )
        }
    }

    return (
        <View style={{ flex: 1, backgroundColor: "rgb(245,248,255)" }}>
            <Tabs
                tabs={tabs}
                onChange={(tab, index) => setActiveTab(index)}
                renderTabBar={(tabProps) => (
                    <View style={{
                        flexDirection: 'row',
                        alignItems: 'center',
                        justifyContent: 'space-evenly',
                    }}>
                        {tabProps.tabs.map((tab, i) => (
                            <TouchableOpacity
                                key={tab.key || i}
                                style={{ padding: 15 }}
                                onPress={() => {
                                    const { goToTab, onTabClick } = tabProps;
                                    onTabClick && onTabClick(tabs[i], i);
                                    goToTab && goToTab(i);
                                }}>
                                <Text style={{
                                    color: tabProps.activeTab === i ? 'rgb(151,206,53)' : 'black',
                                }}>
                                    {tab.title}
                                </Text>
                            </TouchableOpacity>
                        ))}
                    </View>
                )}>
                {tabs.map((tab, index) => renderContent(index))}
            </Tabs>
        </View>
    );
};

const styles = StyleSheet.create({
    order: {
        width: getScreenWidth(),
        padding: 10,
        borderRadius: 10,
        marginBottom: 40,
    },
});

export default MyOrder;
